using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Text.RegularExpressions;
using System;

public class GridEditorWindow : EditorWindow
{
    private string[] labls = new string[4]{"创建地图", "编辑地图", "删除地图", "导出地图"};
    private string[] options = {"blue", "gray", "green", "orange", "red", "yellow"};
    private GameObject cell_root;
    private GameObject cell;
    private GameObject root;
    private GameObject[] objs = {null, null, null, null, null, null};
    private int currSelect;
    private int currType;
    private int confirmId;
    private Sprite sprite;
    private Vector2Int size = new Vector2Int(5, 5);
    private Vector2 cellOffset = new Vector2(4f, -1.5f);
    private Vector2 originPos = new Vector2(-8f, 7f);
    private Dictionary<int, int> idMap = new Dictionary<int, int>();
    private List<int> mapList = new List<int>();
    private string level = "1";
    
    [MenuItem("Tools/GridEditor")]
    public static void Init()
    {
        GridEditorWindow window = EditorWindow.GetWindow<GridEditorWindow>();
        window.minSize = new Vector2(200, 300);
        window.Show();
    }

    private void OnGUI() {
        currSelect = GUILayout.Toolbar(currSelect, labls, GUILayout.Height(50));

        switch(currSelect)
        {
            case 0:
                GUILayout.Space(20);
                cell_root = EditorGUILayout.ObjectField("Cell节点对象", cell_root, typeof(GameObject), true) as GameObject;
                cell = EditorGUILayout.ObjectField("Cell", cell, typeof(GameObject), true) as GameObject;
                GUILayout.BeginHorizontal();

                if(GUILayout.Button("创建地图", GUILayout.ExpandWidth(true)))
                {
                    DeleteAllCell(cell_root);

                    for(int i=0; i<size.x; i++)
                    {
                        for(int j=0; j<size.y; j++)
                        {
                            GameObject obj = GameObject.Instantiate(cell, cell_root.transform);
                            obj.transform.position = new Vector3(originPos.x + j * cellOffset.x, originPos.y + i * cellOffset.y, 0);
                            obj.name = $"row={i},col={j},id={i * size.x + j}";
                            obj.transform.tag = "cell";
                            idMap[i * size.x + j] = -1;
                        }
                    }
                }

                if(GUILayout.Button("删除地图", GUILayout.ExpandWidth(true)))
                {
                    DeleteAllCell(cell_root);
                }
                GUILayout.EndHorizontal();
                break;
            
            case 1:
                for(int i=0; i<objs.Length; i++)
                {
                    objs[i] = EditorGUILayout.ObjectField($"obj_{i}", objs[i], typeof(GameObject), true) as GameObject;
                }
                GUILayout.Space(10);

                currType = EditorGUILayout.Popup("配置类型选择", currType, options);
                if(objs[currType] != null)
                {
                    sprite = objs[currType].GetComponent<SpriteRenderer>().sprite;
                    sprite = EditorGUILayout.ObjectField("预览", sprite, typeof(Sprite), true) as Sprite;
                }
                root = GameObject.Find("Root");
                break;
            
            case 2:
                if(GUILayout.Button("Delete All"))
                {
                    DeleteAllCell(root);
                    for(int i=0; i<size.x * size.y; i++)
                    {
                        idMap[i] = -1;
                    }
                }
                break;

            case 3:
                level = EditorGUILayout.TextField("关卡: ", level);
                if(GUILayout.Button("导出地图", GUILayout.ExpandWidth(true)))
                {
                    mapList.Clear();

                    for(int i=0; i<size.x; i++)
                    {
                        for(int j=0; j<size.y; j++)
                        {
                            int id = i * size.x + j;
                            if(idMap.ContainsKey(id))
                            {
                                mapList.Add(idMap[id]);
                            }
                        }
                    }

                    MapData mapData = new MapData(level, mapList);
                    SaveSystem.Save($"level_{level}.json", mapData);
                }
                break;
        }
    }

    private void DeleteAllCell(GameObject _root)
    {
        while(_root.transform.childCount > 0)
        {
            DestroyImmediate(_root.transform.GetChild(0).gameObject);
        }
    }

    private void OnSelectionChange() {
        if(Selection.activeGameObject != null)
        {
            if(currSelect == 1 && Selection.activeGameObject.transform.tag == "cell")
            {
                Regex regex = new Regex(@"row=(\d+),col=(\d+),id=(\d+)");
                Match match = regex.Match(Selection.activeGameObject.gameObject.name);
                if (match.Success) {
                    int row = int.Parse(match.Groups[1].Value);
                    int col = int.Parse(match.Groups[2].Value);
                    int id = int.Parse(match.Groups[3].Value);
                    idMap[id] = currType;
                    Debug.Log("id = "+id + "mapData = "+currType);
                }

                GameObject obj = GameObject.Instantiate(objs[currType]);
                obj.name = currType.ToString();
                obj.transform.parent = root.transform;
                obj.transform.position = Selection.activeGameObject.transform.position;
                obj.transform.tag = "Clone_cell";
            }

            if(currSelect == 2)
            {
                if(Selection.activeGameObject.transform.tag == "Clone_cell")
                {
                    Regex regex = new Regex(@"row=(\d+),col=(\d+),id=(\d+)");
                    Match match = regex.Match(Selection.activeGameObject.gameObject.name);
                    if (match.Success) {
                        int row = int.Parse(match.Groups[1].Value);
                        int col = int.Parse(match.Groups[2].Value);
                        int id = int.Parse(match.Groups[3].Value);
                        idMap[id] = -1;
                    }

                    DestroyImmediate(Selection.activeGameObject.gameObject);
                }
            }
        }
    }
}
